<template>
  <div>
    <el-backtop :right="50" :bottom="50" style="border: 2px solid #409eff" />
    <div ref="preview-container" class="preview-container">
      <div class="center mc">
        <div class="button-group flex space-between align-items-center">
          <div class="flex space-between no-print">
            <el-button type="danger" @click="router.back()">返回</el-button>
            <el-button type="success" @click="generateQuiz">生成在线问卷</el-button>
            <el-button type="warning" @click="generatePDF">生成本地PDF</el-button>
            <el-popover
              placement="top-start"
              trigger="hover"
              title="不支持生成PDF的题型："
              content="下拉选择题、日期、评分"
              :width="240"
            >
              <template #reference>
                <el-icon color="white" class="no-print" style="transform: translateX(-15px)">
                  <QuestionFilled />
                </el-icon>
              </template>
            </el-popover>
          </div>
          <div class="flex mr-15">
            <el-text class="mx-1">题目数量：{{ store.surveyCount }}</el-text>
            <DarkSwitch class="ml-10 no-print" />
          </div>
        </div>
        <div class="content-group no-border">
          <div class="content mb-10" v-for="(com, index) in store.coms" :key="index">
            <component :is="com.type" :status="com.status" :serialNum="serialNum[index]" />
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="信息" width="500">
      分享链接: <a :href="quizLink" target="_blank">{{ quizLink }}</a>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="copyLink">复制链接</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { QuestionFilled } from '@element-plus/icons-vue';
import { v4 as uuidv4 } from 'uuid';
import { getSurveyById } from '@/db/operation';
import DarkSwitch from '@/components/Common/DarkSwitch.vue';
import { useEditorStore } from '@/stores/useEditor';
import { restoreComponentStatus } from '@/utils';
import { useSurveyNo } from '@/utils/hooks';
import { canUsedForPDF } from '@/types';
import { ElMessage } from 'element-plus';
const store = useEditorStore();
const route = useRoute();
const router = useRouter();
const serialNum = computed(() => useSurveyNo(store.coms).value);
const dialogVisible = ref(false);
const quizLink = ref('');
if (route.params.id) {
  getSurveyById(+route.params.id).then((res) => {
    if (res) {
      restoreComponentStatus(res.coms);
      store.setStore(res);
    }
  });
}

async function generateQuiz() {
  // 1.将问卷的数据传递到server端 server端再存到内存中
  const id = uuidv4();
  await fetch('/api/saveQuiz', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      id,
      quizData: {
        coms: JSON.stringify(store.coms),
        surveyCount: store.surveyCount,
      },
    }),
  });

  // 2.显示弹窗
  dialogVisible.value = true;
  quizLink.value = `${window.location.origin}/quiz/${id}`;
}
function copyLink() {
  dialogVisible.value = false;
  navigator.clipboard.writeText(quizLink.value);
  ElMessage.success('复制成功');
}
function generatePDF() {
  // 1.检查是否有不适合生成PDF的组件，如下拉选择题、日期、评分...
  const result = store.coms.every((item) => canUsedForPDF(item.name));
  if (!result) {
    ElMessage.warning('当前问卷中存在不支持生成PDF的题型，请检查后重试！');
    return;
  }
  // 2.生成PDF
  window.print();
  console.log(result);
}
</script>

<style scoped lang="scss">
.preview-container {
  // width: 100vw;
  min-height: 100vh;
  background: url('@/assets/imgs/editor_background.png');
}
.center {
  width: 800px;
}
.button-group {
  width: 100%;
  height: 60px;
  top: 0;
  left: 0;
  // background-color: var(--white);
  z-index: 100;
}
.content-group {
  padding: 20px;
  position: relative;
  border: 1px solid var(--el-menu-border-color);
  border-radius: var(--border-radius-lg);
  background: var(--el-bg-color);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
@media print {
  .no-print {
    display: none;
  }
  .no-border {
    border: none;
    box-shadow: none;
  }
}
// 去掉页眉页脚及打印链接
@page {
  size: auto;
  margin: 6mm;
}
</style>
